﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using Microsoft.Practices.Unity;
namespace MvcApplication
{
    public class MyDependencyMvcControllerFactory : DefaultControllerFactory  
    {
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)  
        {
            if (controllerType == null)
            {
                throw new HttpException(404,
                    String.Format(
                        CultureInfo.CurrentUICulture,
                        "没有找到路由{0}",
                        requestContext.HttpContext.Request.Path));
            }
            else
            {
                if (!typeof(IController).IsAssignableFrom(controllerType))
                {
                    throw new ArgumentException(
                        String.Format(
                            CultureInfo.CurrentUICulture,
                            "{0}该类型没有继承ControllerBase",
                            controllerType),
                        "controllerType");
                }
                try
                {
                    return (IController)MyUnityContainer.Current.Resolve(controllerType);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException(
                        String.Format(
                            CultureInfo.CurrentUICulture,
                            "{0}创建该controller失败！",
                            controllerType),
                        ex);
                }
            }
        }  
    }  
    
}